<template>
	<view class="container">
		<view class="" v-if="!loading">
			<view class="user-info" @click="show=true">
				<view class="avatar">
					<u-avatar :src="userInfo.avatarUrl"></u-avatar>
				</view>
				<view class="info">
					<text class="nickname">{{userInfo.nickName}}</text>
					<text class="username">ID: {{userInfo._id}}</text>
				</view>
			</view>

			<view class="calendar-section">
				<view class="section-title">本月体重记录日历</view>
				<view class="calendar-wrapper">
					
				</view>
				<view class="calendar-legend" @click="clickto('/pages/index/rili')">
					去查看详情
				</view>
			</view>
			<view class="calendar-section">
				<view class="section-title">本月小伙伴打卡日历</view>
				<view class="calendar-wrapper">
					
				</view>
				<view class="calendar-legend" @click="clickto('/pages/index/rili1')">
					去查看详情
				</view>
			</view>
			<view class="stats-section">
				<view class="section-title">统计信息</view>
				<view class="stats-grid">
					<view class="stats-item">
						<text class="value">{{userInfo.count}}</text>
						<text class="label">记录天数</text>
					</view>
					<view class="stats-item">
						<text class="value">{{userInfo.avg}}kg</text>
						<text class="label">平均体重</text>
					</view>
					<view class="stats-item">
						<text class="value">{{userInfo.maxweight}}kg</text>
						<text class="label">最高体重</text>
					</view>
					<view class="stats-item">
						<text class="value">{{userInfo.minweight}}kg</text>
						<text class="label">最低体重</text>
					</view>
				</view>
			</view>
		</view>
		<u-skeleton rows="2" title :loading="loading" avatar></u-skeleton>
		<!-- 修改信息弹框 -->
		<u-modal :show="show" title="完善信息" :showCancelButton="true" @confirm="confirm" @cancel="show=false"
			:asyncClose="true">
			<form @submit="onSubmit(true, $event)" v-if="userInfo">
				<view class="u-flex u-flex-column u-flex-items-center">
					<button class="u-reset-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
						style="margin-bottom: 20rpx;">
						<u-avatar :src="temptx?temptx:userInfo.avatarUrl"></u-avatar>
					</button>
					<u-input :placeholder="userInfo.nickName" v-model="val" clearable type="nickname">
						<view class="label" slot="prefix">
							用户昵称
						</view>
					</u-input>
				</view>
			</form>
		</u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: null,
				showAvatarPopup: false,
				showPasswordPopup: false,
				passwordForm: {
					oldPassword: '',
					newPassword: '',
					confirmPassword: ''
				},
				val: '',
				show: false,
				passwordRules: {
					oldPassword: [{
						required: true,
						message: '请输入原密码',
						trigger: ['blur', 'change']
					}],
					newPassword: [{
						required: true,
						message: '请输入新密码',
						trigger: ['blur', 'change']
					}],
					confirmPassword: [{
						required: true,
						message: '请确认新密码',
						trigger: ['blur', 'change']
					}]
				},
				startDate: '2024-01-01',
				endDate: '2024-12-31',
				stats: {
					totalDays: 0,
					avgWeight: 0,
					maxWeight: 0,
					minWeight: 0
				},
				temptx: '',
				loading: true
			}
		},
		methods: {
			
			// 获取用户信息
			async getUserInfo() {
				try {
					const {
						result
					} = await uniCloud.callFunction({
						name: 'user',
						data: {
							action: 'getuser',
							token: uni.getStorageSync('jfToken')
						}
					})

					if (result.code === 0) {
						this.userInfo = result.data
						uni.setStorageSync("jfuserinfo", this.userInfo)
						this.loading=false
					}
				} catch (e) {
					uni.showToast({
						title: '获取用户信息失败',
						icon: 'none'
					})
				}
			},
			onChooseAvatar(e) {
				this.temptx = e.detail.avatarUrl
			},
			clickto(url){
				uni.navigateTo({
					url
				})
			},
			async confirm() {

				// 上传图片
				let image = ''
				if (this.temptx) {
					const uploadRes = await uniCloud.uploadFile({
						filePath: this.temptx,
						cloudPath: `tx/${Date.now()}-${Math.random().toString(36).slice(-6)}.jpg`
					})
					image = uploadRes.fileID
				}
				let val = this.val ? this.val : this.userInfo.nickName
				this.updateUserInfo({
					nickName: val,
					avatarUrl: image ? image : this.userInfo.avatarUrl
				})
			},
			onSubmit(confirm, event) {
				if (confirm) {
					try {
						let {
							nickName
						} = event.detail.value;
						this.val = nickName;

					} catch (e) {
						uni.showToast({
							icon: 'none',
							title: e.message
						});
						return;
					}
				}
			},
			// 更新用户信息
			async updateUserInfo(data) {
				try {
					const {
						result
					} = await uniCloud.callFunction({
						name: 'user',
						data: {
							action: 'updateUserProfile',
							token: uni.getStorageSync('jfToken'),
							data
						}
					})

					if (result.code === 0) {
						uni.showToast({
							title: '更新成功',
							icon: 'success'
						})
						await this.getUserInfo() // 刷新用户信息
						this.show = false
					} else {
						uni.showToast({
							title: result.msg,
							icon: 'none'
						})
					}
				} catch (e) {
					uni.showToast({
						title: '更新失败',
						icon: 'none'
					})
				}
			},

			// 修改密码
			async handlePasswordChange() {
				if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
					uni.showToast({
						title: '两次输入的密码不一致',
						icon: 'none'
					})
					return
				}

				try {
					const {
						result
					} = await uniCloud.callFunction({
						name: 'user',
						data: {
							action: 'updatePassword',
							data: {
								oldPassword: this.passwordForm.oldPassword,
								newPassword: this.passwordForm.newPassword
							}
						}
					})

					if (result.code === 0) {
						uni.showToast({
							title: '修改成功',
							icon: 'success'
						})
						this.showPasswordPopup = false
						this.passwordForm = {
							oldPassword: '',
							newPassword: '',
							confirmPassword: ''
						}
					} else {
						uni.showToast({
							title: result.msg,
							icon: 'none'
						})
					}
				} catch (e) {
					uni.showToast({
						title: '修改失败',
						icon: 'none'
					})
				}
			},

			// 退出登录
			handleLogout() {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							// 清除登录信息
							uni.removeStorageSync('token')
							uni.removeStorageSync('userInfo')

							// 跳转到登录页
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}
					}
				})
			},
			dateChange(e) {
				console.log('日期变化：', e)
			},
			dateSelect(e) {
				console.log('选择日期：', e)
			}
		},
		onShow() {
			this.getUserInfo()
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx;

		.user-info {
			background-color: #ffffff;
			border-radius: 20rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;
			display: flex;
			align-items: center;

			.avatar {
				margin-right: 30rpx;
			}

			.info {
				.nickname {
					font-size: 32rpx;
					font-weight: bold;
					display: block;
					margin-bottom: 10rpx;
				}

				.username {
					font-size: 24rpx;
					color: #666;
				}
			}
		}

		.calendar-section {
			background-color: #ffffff;
			border-radius: 20rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.calendar-wrapper {
				width: 100%;
				overflow: hidden;
				margin-bottom: 20rpx;
			}

			.calendar-legend {
				display: flex;
				justify-content: center;
				margin-top: 20rpx;

				.legend-item {
					display: flex;
					align-items: center;
					margin: 0 20rpx;

					.dot {
						width: 20rpx;
						height: 20rpx;
						border-radius: 50%;
						margin-right: 10rpx;

						&.recorded {
							background-color: #018d71;
						}

						&.missed {
							background-color: #ff4d4f;
						}
					}

					text {
						font-size: 24rpx;
						color: #666;
					}
				}
			}
		}

		.stats-section {
			background-color: #ffffff;
			border-radius: 20rpx;
			padding: 30rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.stats-grid {
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				gap: 20rpx;

				.stats-item {
					text-align: center;
					padding: 20rpx;
					background-color: #f8f8f8;
					border-radius: 10rpx;

					.value {
						font-size: 36rpx;
						font-weight: bold;
						color: #018d71;
						display: block;
						margin-bottom: 10rpx;
					}

					.label {
						font-size: 24rpx;
						color: #666;
					}
				}
			}
		}
	}
	.label {
		line-height: 50rpx;
		border-right: 1rpx solid #E6E6E4;
		width: calc(200rpx - 9px);
		margin: calc(20rpx - 6px) 40rpx calc(20rpx - 6px) 0;
		font-family: PingFang-SC, PingFang-SC;
		font-weight: 500;
		font-size: 27rpx;
		color: #333333;
		text-align: center;
	}
</style>